﻿/*!2018-04-09 */ ! function () {
    //页面加载完毕 验证是否有cm统计js代码,没有则引入
    window.onload = function () {
        if (typeof (cmCreateElementTag) == "undefined") {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "//pics.lvjs.com.cn/min/index.php?f=/js/v5/ibm/eluminate.js,/js/v5/ibm/coremetrics-initalize.js&v=040914";
            document.body.appendChild(script);
        }
    };
}();

function novaAppendHTML(dom, html) {
    var divTemp = document.createElement("div"), nodes = null
      // 文档片段，一次性append，提高性能
      , fragment = document.createDocumentFragment();
    divTemp.innerHTML = html;
    nodes = divTemp.childNodes;
    for (var i=0, length=nodes.length; i<length; i+=1) {
        fragment.appendChild(nodes[i].cloneNode(true));
    }
    dom.appendChild(fragment);
    // 据说下面这样子世界会更清净
    nodes = null;
    fragment = null;
}



function html_str(channel_info,place_info,ads_info){
    var _html = place_info.html_code;
    var li_reg = /\[([^\[]*)\]/gi;
    var li_del_reg = /\[(.*)\]/g;
    var li_html = _html.match(li_reg);

    var url_reg = /\{\$clickurl\}/g;
    var img_reg = /\{\$pic\}/g;
    var cmt_reg = /cmCreateElementTag/g;
    var del_reg = /\[[1-9]\$/g;
    var del_reg2 = /\$\]/g;
    var html = "";
    var ids_arr = new Array();
    for(var i=0;i<ads_info.length;i++){
        if(li_html[i]){
            li_html[i] = li_html[i].replace(url_reg,ads_info[i].url);
            li_html[i] = li_html[i].replace(img_reg,(ads_info[i].image).replace(/http:\/\/((pic\.lvmama\.com)|(((s[\d])|(pics))\.lvjs\.com\.cn))/,"//pics.lvjs.com.cn"));
            li_html[i] = li_html[i].replace(cmt_reg,'cmCreateElementTag('+'\'PC_广告系统_ONCLICK\',\''+channel_id+'_'+place_id+'_'+dest_id+'_'+ads_info[i].id+'\');bnnerClick(\''+channel_info.channel_name+'\',\''+place_info.place_name+'\',\'广告系统\',\''+ads_info[i].id+'\',\''+ads_info[i].name+'\',\''+(i+1)+'\',\''+ads_info[i].url+'\');');
            li_html[i] = li_html[i].replace(del_reg,"");
            li_html[i] = li_html[i].replace(del_reg2,"");
            html += li_html[i];
            ids_arr[i]=ads_info[i].id;
        }
    }
    if(ids_arr.length>0) ads_view(ids_arr);
    html = _html.replace(li_del_reg,html);
    return html;
}

function ads_view(ids_arr){
    window.onload = function () {
        if (typeof (cmCreateElementTag) != "undefined") {
            for (var index = 0; index < ids_arr.length; index++) {
                cmCreateElementTag('PC_广告系统_VIEW',channel_id+"_"+place_id+"_"+dest_id+"_"+ids_arr[index]);
            }
        }
    };
}





//格式化参数
function formatParams(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    arr.push(("v=" + Math.random()).replace(".",""));
    return arr.join("&");
}
//jsonp
function adsShow(channel_id, place_id, dest_id) {
    // var data = {dest_id:1, channel_id: 1,place_id:33,jsonpCallback:'jsonpCallback'};
    var data = {dest_id:dest_id, channel_id: channel_id,place_id:place_id,jsonpCallback:'jsonpCallback'};
    var params = formatParams(data);
    var url = "//www.lvmama.com/php-seo/ads/ex";
    url = url + '?' + params;
    var script = document.createElement('script');
    script.setAttribute('src',url);
    document.getElementsByTagName('head')[0].appendChild(script);

}
//回调函数
function jsonpCallback(data){
    if (data.code == 200) {
        //拼接html广告代码
        // document.getElementById('ads_'+channel_id+'_'+place_id+'_'+dest_id).parentNode.innerHTML += html_str(data.msg.place_info,data.msg.ads_info);
        try {
            var ulLiStr = html_str(data.msg.channel_info,data.msg.place_info, data.msg.ads_info);
            var wrapElementId = 'ads_' + channel_id + '_' + data.msg.ads_info[0].place_id + '_' + dest_id;
            var wrapElement = document.getElementById(wrapElementId);
            novaAppendHTML(wrapElement.parentNode, ulLiStr);
        } catch (e) {
        }
    } else {
        console.log('广告参数错误，不加载，错误信息：' + data.msg);


    }
}
// function adsShow(channel_id, place_id, dest_id) {
//     ajax({
//         url: "http://www.lvmama.com/php-seo/ads/ex",
//         type: "get",                       //请求方式
//         data: {dest_id:dest_id, channel_id: channel_id,place_id:place_id },        //请求参数
//         dataType: "json",
//         timeout:3000,
//         success: function (response, xml) {
//             var data = eval("(" + response + ")");
//             // 此处放成功后执行的代码
//             if (data.code == 200) {
//                 //拼接html广告代码
//                 // document.getElementById('ads_'+channel_id+'_'+place_id+'_'+dest_id).parentNode.innerHTML += html_str(data.msg.place_info,data.msg.ads_info);
//                 try {
//                     var ulLiStr = html_str(data.msg.place_info, data.msg.ads_info)
//                     var wrapElementId = 'ads_' + channel_id + '_' + place_id + '_' + dest_id
//                     var wrapElement = document.getElementById(wrapElementId)
//                     novaAppendHTML(wrapElement.parentNode, ulLiStr)
//                 } catch (e) {
//                 }
//                 //console.log('广告加载');
//             } else {
//                 console.log('广告参数错误，不加载，错误信息：' + data.msg);
//             }
//         },
//         fail: function (status) {

//             // 此处放失败后执行的代码
//         }
//     });
// }
// function ajax(options) {
//     options = options || {};
//     options.type = (options.type || "GET").toUpperCase();
//     options.dataType = options.dataType || "json";
//     options.timeout = options.timeout || 5000;
//     var params = formatParams(options.data);

//     //创建 - 非IE6 - 第一步
//     if (window.XMLHttpRequest) {
//         var xhr = new XMLHttpRequest();
//     } else { //IE6及其以下版本浏览器
//         var xhr = new ActiveXObject('Microsoft.XMLHTTP');
//     }


//     //接收 - 第三步
//     xhr.onreadystatechange = function () {
//         if (xhr.readyState == 4) {
//             var status = xhr.status;
//             if (status >= 200 && status < 300) {
//                 options.success && options.success(xhr.responseText, xhr.responseXML);
//             } else {
//                 options.fail && options.fail(status);
//             }
//         }
//     }
//     //连接 和 发送 - 第二步
//     if (options.type == "GET") {
//         xhr.open("GET", options.url + "?" + params, true);
//         xhr.timeout = options.timeout; // 超时时间，单位是毫秒
//         xhr.send(null);
//     } else if (options.type == "POST") {
//         xhr.open("POST", options.url, true);
//         xhr.timeout = options.timeout; // 超时时间，单位是毫秒
//         //设置表单提交时的内容类型
//         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//         xhr.send(params);
//     }
// }
